package cn.itcast.bos.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.IPermissionService;
import cn.itcast.bos.service.system.IRoleService;
import cn.itcast.bos.service.system.IUserService;

//自定义Realm
//@Service("bosRealm")
public class BosRealm extends AuthorizingRealm{
	@Autowired
	private IRoleService roleService;
	
	@Autowired IPermissionService permissionService;
	
	@Autowired
	private IUserService userService;
	
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("shiro 授权管理...");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 根据当前登录用户 查询对应角色和权限
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		// 调用业务层，查询角色
		List<Role> roles = roleService.findByUser(user);
		for (Role role : roles) {
			authorizationInfo.addRole(role.getKeyword());
		}
		// 调用业务层，查询权限
		List<Permission> permissions = permissionService.findByUser(user);
		for (Permission permission : permissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}

		return authorizationInfo;
	}

	@Override	//认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("认证");
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		System.out.println(usernamePasswordToken.getUsername());
		System.out.println(usernamePasswordToken.getPassword());
		
		//根据用户名查询用户信息
		User user = userService.findByUsername(usernamePasswordToken.getUsername());
		System.out.println("user:" + user);
		if (user == null) {
			System.out.println("=======================1");
			//用户名不存在
			//参数1：期望登录后，保存在Subject中信息
			//参数2：密码，如果返回为null，表示不存在
			//参数3: realm名称
			//return new SimpleAuthenticationInfo(user, null, getName());
			return null;
		} else {
			System.out.println("=======================2");
			//用户名存在
			//当返回用户密码时，securityManager安全管理器
			//自动比较返回的密码与用户输入密码是否一致
			//如果一致，登陆成功，否则报用户名错误异常
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
 		
	}

}
